import { observer } from 'mobx-react-lite';
import { Button, Dialog, Form, Input, isArray, Select, Toast } from 'esy-ui';
import { useCallback, useState } from 'react';
import { Header } from '@/components';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import { form_ipt_com, form_lable } from '@/styles/esy-ui';
import { useFormatText } from '@/hooks';
import { forms } from './const';
import SendCode from './SendCode';
import { postBindEmail, postBindMobile, postSendVerfiyCode, postUpdateFundPwd, postUpdateLoginPwd } from '@/services';

const FormItem = Form.Item;

function AddEdit({ text, isShow = true, onOpen }: any) {
  if (!isShow) return null;

  return (
    <div className='px-3 bg-color-21 text-white py-1 rounded ml-2' onClick={onOpen}>
      {text}
    </div>
  );
}
const mobile = {
  text: 'text_110',
  value: '2',
};
const email = {
  text: 'text_111',
  value: '3',
};

const bindTypes = (userInfo, _text, setBindInfo) => {
  const arr = [];
  if (userInfo?.Mobile) {
    arr.push({ ...mobile, text: _text(mobile.text) });
  }
  if (userInfo?.Email) {
    arr.push({ ...email, text: _text(mobile.text) });
  }
  setTimeout(() => {
    setBindInfo(userInfo?.Mobile || userInfo?.Email);
  }, 150);
  return arr;
};

function AccountSafety() {
  const { userInfo, changeUserInfo } = useUserInfoStore();
  const { changeState } = useGlobalStore();
  const { text } = useFormatText();
  const [dialogKey, setDialogKey] = useState('');
  const [form] = Form.useForm();

  // 当修改资金密码时，切换绑定方式自动切换对应的绑定值
  const setBindInfo = (val) => {
    form.setFieldValue('BindInfo', val);
  };

  // 打开弹窗
  const onOpen = useCallback((k: string) => () => setDialogKey(k), []);

  // 关闭弹窗
  const onClose = useCallback(() => {
    setDialogKey('');
  }, []);

  // 发送验证码
  const onSender = useCallback(
    (_cn) => {
      const BindInfo = form.getFieldValue('BindInfo');
      let Type = null;
      let SendType = 1;
      // 资金密码修改
      if (dialogKey === 'editFundPwd') {
        SendType = 4;
        Type = form.getFieldValue('Type') === '2' ? 2 : 3;
      } else if (dialogKey === 'bindMobile') {
        Type = 2;
      } else if (dialogKey === 'bindEmail') {
        Type = 3;
      }
      if (!BindInfo) {
        Toast.show({ content: text('text_88') });
      } else {
        postSendVerfiyCode({ BindInfo, Type, SendType })
          .then(() => {
            _cn && _cn();
          })
          .catch(() => {});
      }
    },
    [dialogKey, form, text],
  );

  const onSubmit = () => {
    changeState('isLoading', true);
    form
      .validate()
      .then((values) => {
        if (Object.values(values).some((it) => !it)) {
          Toast.show({ content: text('text_88') });
          changeState('isLoading', false);
        } else {
          // 根据不同的分类赋值api
          let api;
          switch (dialogKey) {
            case 'bindMobile':
              api = postBindMobile;
              break;
            case 'bindEmail':
              api = postBindEmail;
              break;
            case 'editPwd':
              api = postUpdateLoginPwd;
              break;
            case 'editFundPwd':
              api = postUpdateFundPwd;
              break;
            default:
              break;
          }
          if (api) {
            api(values)
              .then(() => {
                // 资金密码修改
                if (dialogKey === 'bindMobile') {
                  changeUserInfo({ IsFund: true } as any);
                }
                // 绑定手机更新
                if (dialogKey === 'bindMobile') {
                  changeUserInfo({ Mobile: values.BindInfo } as any);
                }
                // 绑定邮箱更新
                if (dialogKey === 'bindEmail') {
                  changeUserInfo({ Email: values.BindInfo } as any);
                }
                Toast.show({ content: text('text_129') });
                onClose();
              })
              .catch(() => {})
              .finally(() => {
                changeState('isLoading', false);
              });
          } else {
            changeState('isLoading', false);
          }
        }
      })
      .catch(() => {
        changeState('isLoading', false);
      });
  };

  return (
    <div className='bg-body-2 w-full h-full flex flex-col'>
      <Header title='text_109' />
      <div className='px-4 py-3 flex flex-col flex-1'>
        <div className='text-sm my-3'>
          {text('username')}：{userInfo?.Account}
        </div>
        <div className='flex-1'>
          <div className='flex items-center my-3'>
            <div className={form_lable}>{text('text_110')}</div>
            <Input disabled value={userInfo.Mobile || '--'} classNames={form_ipt_com} suffix={<AddEdit isShow={!userInfo.Mobile} text={text('text_114')} onOpen={onOpen('bindMobile')} />} />
          </div>
          {userInfo.Mobile ? (
            <div className='text-error text-xs mb-3'>
              *{text('text_110')}
              {text('text_116')}
            </div>
          ) : null}

          <div className='flex items-center  my-3'>
            <div className={form_lable}>{text('text_111')}</div>
            <Input value={userInfo.Email || '--'} disabled classNames={form_ipt_com} suffix={<AddEdit isShow={!userInfo.Email} text={text('text_114')} onOpen={onOpen('bindEmail')} />} />
          </div>
          {userInfo.Email ? (
            <div className='text-error text-xs mb-3'>
              *{text('text_111')}
              {text('text_116')}
            </div>
          ) : null}

          <div className='flex items-center my-3'>
            <div className={form_lable}>{text('text_112')}</div>
            <Input value='******' disabled classNames={form_ipt_com} suffix={<AddEdit text={text('text_115')} onOpen={onOpen('editPwd')} />} />
          </div>

          <div className='flex items-center my-3'>
            <div className={form_lable}>{text('text_113')}</div>
            <Input
              value={userInfo.IsFund ? '******' : '--'}
              disabled
              classNames={form_ipt_com}
              suffix={<AddEdit isShow={userInfo.Email || userInfo.Name} text={text('text_115')} onOpen={onOpen('editFundPwd')} />}
            />
          </div>
          {!userInfo.Email && !userInfo.Name ? <div className='text-error text-xs mb-3'>*{text('text_131')}</div> : null}

          {/* <div className='flex items-center my-3'>
            <div className={form_lable}>{text('text_117')}</div>
            <Input value={userInfo.IsFund ? '******' : '--'} disabled classNames={form_ipt_com} suffix={<AddEdit text={text('text_114')} onOpen={onOpen('bindEmail')} />} />
          </div>
          <div className='flex items-center my-3'>
            <div className={form_lable}>{text('text_118')}</div>
            <Input value={userInfo.IsFund ? '******' : '--'} disabled classNames={form_ipt_com} suffix={<AddEdit text={text('text_114')} onOpen={onOpen('bindEmail')} />} />
          </div> */}
        </div>
      </div>
      <Dialog open={Boolean(dialogKey)} onClose={onClose} direction='bottom'>
        <div className='bg-white min-h-56 rounded-t-lg p-3 flex flex-col'>
          <div className='text-sm my-3 text-center'>{text(forms[dialogKey]?.title)}</div>
          <Form className='flex-1 flex flex-col' form={form}>
            <div className='flex-1'>
              {isArray(forms[dialogKey]?.formItmes) &&
                forms[dialogKey]?.formItmes.map((it) => {
                  if (it.itemType === 'bindType') {
                    return (
                      <FormItem name={it.name} key={it.label} formlabel={text(it.label)} initialValue={it.default || ''}>
                        <Select
                          classNames={{ input: form_ipt_com }}
                          options={bindTypes(userInfo, text, setBindInfo)}
                          onSelect={(e) => {
                            form.setFieldValue('BindInfo', e.value === '2' ? userInfo?.Mobile : userInfo?.Email);
                          }}
                        />
                      </FormItem>
                    );
                  }
                  return (
                    <FormItem name={it.name} key={it.label} formlabel={text(it.label)}>
                      <Input disabled={it.disabled} type={it.type} classNames={form_ipt_com} maxLength={it.isSend ? 6 : 99} suffix={it.isSend ? <SendCode onSender={onSender} /> : it.suffix} />
                    </FormItem>
                  );
                })}
            </div>
            <Button className='rounded mt-3' htmltype='submit' onClick={onSubmit}>
              {text('text_93')}
            </Button>
          </Form>
        </div>
      </Dialog>
    </div>
  );
}

export default observer(AccountSafety);
